import axios, { AxiosRequestHeaders, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { useUserStore } from "../store/user";
import { layer } from '@layui/layui-vue';
import router from '../router'

let baseURL = '';
if (import.meta.env.MODE == 'production') {

} else {
  baseURL = import.meta.env.VITE_BASE_URL;
}

type TAxiosOption = {
  timeout: number;
  baseURL: string;
}

const config: TAxiosOption = {
  timeout: 5000,
  baseURL,
  // baseURL: "http://localhost:8080"
}

class Http {
  service;
  constructor(config: TAxiosOption) {
    this.service = axios.create(config)

    /* 请求拦截 */
    this.service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
      if (config.url?.startsWith('/api/')) {
        config.baseURL = baseURL;
        // config.url = config.url.replace('/aiApi/', '/');
      }
      else if (config.url?.startsWith('/admin/')) {
        config.baseURL = baseURL;
        // config.url = config.url.replace('/ttsApi/', '/');
      }

      const userInfoStore = useUserStore();
      if (userInfoStore.token) {
        (config.headers as AxiosRequestHeaders).Authorization = 'Bearer ' + userInfoStore.token as string
      } else {
        if (router.currentRoute.value.path !== '/login') {
          router.push('/login');
        }
      }
      return config
    }, error => {
      return Promise.reject(error);
    })

    /* 响应拦截 */
    this.service.interceptors.response.use((res: AxiosResponse<any>) => {
      // 二进制数据则直接返回
      if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
        return res.data
      }

      if (res.status >= 200 && res.status < 300) {
        // 返回响应数据
        switch (res.data.code) {
          case 200:
            return res.data;
          case 500:
            return res.data;
          case 99998:
            layer.confirm(
              '会话超时, 请重新登录',
              {
                icon: 2, yes: function () {
                  router.push('/login');
                  layer.closeAll()
                }
              });
            return res.data;
          default:
            break;
        }
        return Promise.resolve(res.data);
      } else {
        // 处理错误
        throw new Error(res.statusText);
      }

    }, error => {
      if (error?.response?.status === 401) {
        layer.msg(error?.response?.data?.msg || 'token 过期', { icon: 2, time: 1000 }, () => {
          router.push('/login');
          layer.closeAll()
        })
      }
      else if (error?.response?.status === 404) {
        layer.msg(error?.response?.data || '404', { icon: 2, time: 2000 });
      } else {
        layer.msg(error?.response?.data?.msg || '系统错误', { icon: 2, time: 2000 })
      }
      return Promise.reject(error)
    })
  }

  /* GET 方法 */
  get<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.get(url, { params, ..._object })
  }
  /* POST 方法 */
  post<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.post(url, params, _object)
  }
  /* PUT 方法 */
  put<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.put(url, params, _object)
  }
  /* DELETE 方法 */
  delete<T>(url: string, params?: any, _object = {}): Promise<any> {
    return this.service.delete(url, { params, ..._object })
  }
}

export default new Http(config)

const http = new Http(config);

export {
  http as request
}